package com.example.mallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.example.mallauthserver.VO.SocialUser;
import com.example.mallauthserver.fefin.MembeFeginService;
import com.msb.common.constant.AuthConstant;
import com.msb.common.utils.HttpUtils;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: xixifeng
 * @Date: 2022/11/8 - 11 - 08 - 13:51
 * @Description: com.example.mallauthserver.controller
 * @version: 1.0
 */
@Controller
public class Auth2Controller {

    @Autowired
    MembeFeginService membeFeginService;

    /**
     * 第三方登入（社交登入）
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping("/oauth/weibo/success")
    public String weiBoAuth(@RequestParam("code") String code
                            , HttpSession httpSession
                            , HttpServletResponse httpServletResponse) throws Exception {

        Map<String, String> body = new HashMap<>();
        body.put("client_id","1156045269");
        body.put("client_secret","fff37afefd0aadf65ad630be32cad593");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://auth.msb.com:30000/oauth/weibo/success");
        body.put("code",code);
        //根据code获取对应的Token信息
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com"
                , "/oauth2/access_token"
                , "post"
                , new HashMap<>()
                , null
                , body
        );
        int statusCode = post.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // 说明获取Token失败,就调回到登录页面
            return "redirect:http://auth.msb.com:30000/login.html";
        }
        // 说明获取Token信息成功
        HttpEntity entity = post.getEntity();
        String json = EntityUtils.toString(entity);
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

        R r = membeFeginService.socialLogin(socialUser);

        if (r.getcode() != 0) {
            // 登录错误
            return "redirect:http://auth.msb.com:30000/login.html";
        }
        // 注册成功就需要调整到商城的首页
       String entity1 = (String) r.get("entity");
       MemberVO memberVO = JSON.parseObject(entity1, MemberVO.class);
       httpSession.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
        return "redirect:http://mall.msb.com:8040/home";
    }





}
